<script setup lang="ts">
import { ref } from 'vue'

const items = ref<{ id: number; name: string; isReplacing: boolean }[]>([
  { id: 1, name: 'Item 1', isReplacing: false },
  { id: 2, name: 'Item 2', isReplacing: false },
  { id: 3, name: 'Item 3', isReplacing: false },
])
const nextId = ref(4)

function removeItem(item: any) {
  const index = items.value.findIndex((i) => i.id === item.id)
  if (index !== -1) {
    // 标记为正在替换
    items.value[index].isReplacing = true

    setTimeout(() => {
      // 移除旧项，并在同一位置添加新项
      items.value.splice(index, 1, {
        id: nextId.value,
        name: `New Item ${nextId.value}`,
        isReplacing: false,
      })
      nextId.value++
    }, 500) // 确保这个延时与.fade-leave-active的持续时间一致
  }
}

const inter = ref()
onMounted(() => {
  inter.value = setInterval(() => {
    let ran = Math.floor(Math.random() * 3)
    let id = items.value[ran]
    removeItem(id)
  }, 3000)
})
onUnmounted(() => {
  clearInterval(inter.value)
})
</script>

<template>
  <div>
    <transition-group name="fade" tag="ul">
      <template v-for="(item, index) in items" :key="index">
        <view v-if="!item.isReplacing" @click="removeItem(item)">
          <li style="display: inline-block">{{ index }},</li>
          <li style="display: inline-block">
            {{ item.name }}
          </li>
        </view>
      </template>
    </transition-group>
    <!-- <button @click="addItem">Add Item</button> -->
  </div>
</template>

<style lang="scss" scoped>
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0.1;
}
</style>
